package com.takepoints.mobile;

import org.json.JSONObject;
import org.json.JSONTokener;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.FacebookVO;
import com.facebook.android.SessionStore;
import com.facebook.android.Facebook.DialogListener;
import com.takepoints.android.TPConst;
import com.takepoints.android.services.SecurityServices;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class UserLogin extends BaseActivity {
	
	private Facebook facebook = null;
	private Handler handler = null;
	private String[] PERMISSIONS = new String[]{ "publish_stream", "read_stream", "offline_access", "email" };
	
	private EditText txtUsrname = null;
	private EditText txtPasswd = null;
	private Button btnAccess = null;
	private TextView lnkRegister = null;
	private ImageView btnFbLogin = null;
	
	private ProgressDialog progressDlg = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.login);
        manageMenu(0);
        
        Bundle bundle = this.getIntent().getExtras();
    	final String pageSrc = bundle.getString("pageSrc");

		facebook = new Facebook("260050780743981");
		facebook.setAccessToken(Facebook.TOKEN);
        handler = new Handler();
    	
    	txtUsrname = (EditText)findViewById(R.id.txtUsrname);
    	txtPasswd = (EditText)findViewById(R.id.txtPasswd);
    	
    	String prefUsrname = getSharedStringValue(TPConst.PRF_USRNAME);
    	if(prefUsrname != null && prefUsrname.trim().length() > 0){
	    	txtUsrname.setText(prefUsrname);
	    	txtUsrname.setSelection(txtUsrname.getText().length());
    	} else{
    		popup("หากมี Facebook กดปุ่ม \"F Login\" ได้เลย !");
    	}
    	
    	String prefPasswd = getSharedStringValue(TPConst.PRF_PASSWD);
    	if(prefPasswd != null && prefPasswd.trim().length() > 0){
    		txtPasswd.setText(prefPasswd);
    		txtPasswd.setSelection(txtPasswd.getText().length());
    	}
    	
    	btnAccess = (Button)findViewById(R.id.btnAccess);
    	btnAccess.setOnClickListener(new View.OnClickListener(){
    		public void onClick(View view) {
				 String uname = txtUsrname.getText().toString().toLowerCase();
				 String paswd = txtPasswd.getText().toString();
				 
				 int memId = SecurityServices.verifyUser(uname, paswd);
				 if(memId > 0){
					 Editor editor = sharePref.edit();
					 editor.putString(TPConst.PRF_USRNAME, uname);
					 editor.putString(TPConst.PRF_PASSWD, paswd);
					 editor.putInt(TPConst.PRF_MEMBER_ID, memId);
					 editor.commit();
					 
					 popup("Login สำเร็จ");
					 
					 Intent settingInt = null;
					 if("SETTING".equals(pageSrc)){
						 settingInt = new Intent(view.getContext(), Setting.class);
					 } else{
						 settingInt = new Intent(view.getContext(), Takepoints.class);
					 }
					 startActivityForResult(settingInt, 0);
				 } else{
					 popup("Login failed, Please try again !");
				 }
			}
    	});

    	lnkRegister = (TextView)findViewById(R.id.lnkRegister);
    	lnkRegister.setOnClickListener(new View.OnClickListener(){
  			 public void onClick(View view) {
  				 Intent regisInt = new Intent(view.getContext(), UserRegister.class);
  				 startActivityForResult(regisInt, 0);
  			 }
      	});

    	SessionStore.restore(facebook, this);
    	btnFbLogin = (ImageView)findViewById(R.id.btnFbLogin);
		btnFbLogin.setOnClickListener(new View.OnClickListener(){
    		public void onClick(View view) {
    			if(facebook.isSessionValid()){
    				confirmLogoutDlg();
    			} else{
    				onFacebookClick();
    			}
    		}
    	});
		
    	if(facebook.isSessionValid()){
    		txtUsrname.setEnabled(false);
    		txtPasswd.setEnabled(false);
    		btnAccess.setEnabled(false);
    		lnkRegister.setVisibility(TextView.INVISIBLE);
    		btnFbLogin.setImageResource(R.drawable.fblogout);
    	} else{
    	}
	}
	
	private void onFacebookClick(){
		/*Intent intent = new Intent(view.getContext(), MyProfile.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
		*/
		/*
		facebook.authorize(this, new String[]{ "offline_access", "publish_stream", "email" }, 
			new DialogListener() {
		           @Override
		           public void onComplete(Bundle values) {
		        	   String token = facebook.getAccessToken();  //get access token
		        	    alert(token);
		           }
	
		           @Override
		           public void onFacebookError(FacebookError error) {}
	
		           @Override
		           public void onError(DialogError e) {}
	
		           @Override
		           public void onCancel() {}
			}
		);
		*/
		//facebook.authorize(this, PERMISSIONS, -1, new DialogListener() {
		
		facebook.authorize(this, PERMISSIONS, new DialogListener() {
            @Override
            public void onComplete(Bundle values) {
            	progressDlg = ProgressDialog.show(UserLogin.this, "Takepoints.com", "Loging in ...", true);
            	
            	new Thread() {
        			@Override
        			public void run() {
		            	try {
		            		FacebookVO fb = new FacebookVO();
		            		
							String me = facebook.request("me");
							JSONObject jsonObj = (JSONObject) new JSONTokener(me).nextValue();
							
							fb.setId(jsonObj.getString("id"));
							fb.setName(jsonObj.getString("name"));
							fb.setFirstName(jsonObj.getString("first_name"));
							fb.setLastName(jsonObj.getString("last_name"));
							fb.setGender(jsonObj.getString("gender"));
							fb.setEmail(jsonObj.getString("email"));
							
							String birthDay = "";
							try{
								fb.setBirthday(jsonObj.getString("birthday"));
								birthDay = fb.getBirthday();
							} catch(Exception e){
								fb.setBirthday(e.getMessage());
							}
							SessionStore.save(facebook, UserLogin.this);
							SessionStore.saveFbId(fb.getId(), UserLogin.this);
							SessionStore.saveName(fb.getName(), UserLogin.this);
							SessionStore.saveInfo(fb, UserLogin.this);

							final String email = fb.getEmail();
							final int memId = SecurityServices.loginWithFB(fb.getId(), fb.getFirstName(), fb.getLastName(), fb.getGender(), birthDay, email);
							//URL imgUrl = new URL("https://graph.facebook.com/" + fb.getId() + "/picture");
							//final Bitmap imgFB = BitmapFactory.decodeStream(imgUrl.openConnection().getInputStream());
							//imgMember.setImageDrawable(getPictureForFacebookId(id));
							
							handler.post(new Runnable() {
	                            @Override
	                            public void run() {
	                            	EditText txtUsrname = (EditText)findViewById(R.id.txtUsrname);
	                            	txtUsrname.setText( email );
	                            	
	                            	EditText txtPasswd = (EditText)findViewById(R.id.txtPasswd);
	                            	txtPasswd.setText( "0000" );
	                            	
	                            	if(memId > 0){
    									 Editor editor = sharePref.edit();
    									 editor.putString(TPConst.PRF_USRNAME, email);
    									 editor.putString(TPConst.PRF_PASSWD, "0000");
    									 editor.putInt(TPConst.PRF_MEMBER_ID, memId);
    									 editor.commit();
    									 popup("Login สำเร็จ");
    								}
	                            	progressDlg.dismiss();
	                            	onBackPressed();
	                            }
	                        });
						} catch (Exception e) {
						}
        			}
        		}.start();
            	
            }
            @Override
            public void onFacebookError(FacebookError error) {}
            @Override
            public void onError(DialogError e) {}
            @Override
            public void onCancel() {}
        });
	}
	
	private void confirmLogoutDlg(){
		AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
		alertbox.setMessage("คุณต้องการที่จะ Logout ใช่หรือไม่ ?");
		alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				fbLogout();
			}
		});
		alertbox.setNeutralButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dlgInf, int which) {
				dlgInf.dismiss();
			}
		});
		alertbox.show();
    }
	
	private void fbLogout() {
    	progressDlg = ProgressDialog.show(UserLogin.this, "Takepoints.com", "Disconnecting from Facebook ...", true);
		new Thread() {
			@Override
			public void run() {
				SessionStore.clear(UserLogin.this);
				int what = 1;
				try {
					facebook.logout(UserLogin.this);
					what = 0;
				} catch (Exception ex) {
					//ex.printStackTrace();
				}
				mHandler.sendMessage(mHandler.obtainMessage(what));
			}
		}.start();
	}
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			progressDlg.dismiss();
			if (msg.what == 1) {
				popup("Facebook logout failed");
			} else {
				Editor editor = sharePref.edit();
				editor.remove(TPConst.PRF_USRNAME);
				editor.remove(TPConst.PRF_PASSWD);
				editor.remove(TPConst.PRF_MEMBER_ID);
				editor.commit();
				 
				txtUsrname.setText("");
				txtUsrname.setEnabled(true);
				
				txtPasswd.setText("");
	    		txtPasswd.setEnabled(true);
	    		
	    		btnAccess.setEnabled(true);
	    		lnkRegister.setVisibility(TextView.VISIBLE);
	    		btnFbLogin.setImageResource(R.drawable.fblogin);
	    		
				popup("Logout แล้ว !");
			}
		}
	};
	
	@Override
	public void onBackPressed(){
		Intent homeInt = new Intent(this, Takepoints.class);
		startActivity(homeInt);
		finish();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    facebook.authorizeCallback(requestCode, resultCode, data);
	}
	
}
